<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/11/23
 * Time: 14:36
 */
namespace App\Models;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redis;

class AllInPay{
    
    public static function Config()
    {
        $config['appid'] = '00003611';
        $config['cusid'] = '201421048162693';
        $config['appkey'] = env('ALLINPAY_APPKEY');
        $config['apiurl'] = "https://vsp.allinpay.com/apiweb/unitorder";//生产环境
        $config['apiversion'] = '11';
        return $config;
    }
    //老版本充值
    public static function allinpayRecharge($userid,$money,$paytype = '2',$openid = '') {
        if(!$userid || !$money || !$paytype || ($paytype!='1' && $paytype != '2')) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        if(!$openid) {
            $openid = Auth::user()->openid;
        }
        $data['userid'] = $userid;
        $data['money'] = $money;
        $mobile = User::where('id',$userid)->pluck('mobile')->first();
        if($mobile) {
            $mobile = substr($mobile,8,10);
            $rand = '';
            for($i=0;$i<4;$i++){
                $rand .= rand(0,9);
            }
            $ordernumber=$paytype.date('ymdHis',time()).$rand.$mobile;
            Redis::setex('Recharge:OrderNumber:'.$ordernumber,86400,json_encode($data));
            unset($data);
        } else {
            return ['status'=>'failed','message'=>'无法找到该用户！'];
        }
        $params = array();
        $params["cusid"] = self::Config()['cusid'];
        $params["appid"] = self::Config()['appid'];
        $params["version"] = self::Config()['apiversion'];
        $params["trxamt"] = $money * 100;
        $params["reqsn"] = $ordernumber;//订单号,自行生成
        $params["paytype"] = "W02";
        $params["randomstr"] = rand(100000000000000,999999999999999);//
        $params["body"] = '翻贝网-'.$ordernumber;
        $params["remark"] = $userid;
        $params["acct"] = $openid;
//        $params["limit_pay"] = "no_credit";
        $params["notify_url"] = env('WEB_URL')."fbwnotify/allinpaynotify";
        $params["sign"] = self::SignArray($params);//签名
        $paramsStr = self::ToUrlParams($params);
        $url = self::Config()['apiurl'] . "/pay";
        $rsp = self::request($url, $paramsStr);
        $rspArray = json_decode($rsp, true);
        $data['jsApiParameters'] = $rspArray['payinfo'];
        $data['ordernumber'] = $ordernumber;
        if(self::validSign1($rspArray)){
            return ['status'=>'success','data'=>$data];
        }
        return false;;
    }
    //新版本充值
    public static function allinpayRechargeByV2Version($userid,$money,$paytype = '2',$openid = '') {
        if(!$userid || !$money || !$paytype || ($paytype!='1' && $paytype != '2')) {
            return ['status'=>'failed','message'=>'参数错误！'];
        }
        if(!$openid) {
            $openid = Auth::user()->openid;
        }
        $data['userid'] = $userid;
        if(Auth::user()->isdouble == 1) {
            $fee = 0.00;
            $actualMoney = $money;
        } else {
            $fee = env('RECHARGE_FEE') * $money;
            $actualMoney = (1+env('RECHARGE_FEE')) * $money;
        }
        $data['money'] = $money;
        $data['fee'] = $fee;
        $data['actualmoney'] = $actualMoney;
        $data['apiversion'] = 'v2';
        $mobile = User::where('id',$userid)->pluck('mobile')->first();
        if($mobile) {
            $mobile = substr($mobile,8,10);
            $rand = '';
            for($i=0;$i<4;$i++){
                $rand .= rand(0,9);
            }
            $ordernumber=$paytype.date('ymdHis',time()).$rand.$mobile;
            Redis::setex('Recharge:OrderNumber:'.$ordernumber,86400,json_encode($data));
            unset($data);
        } else {
            return ['status'=>'failed','message'=>'无法找到该用户！'];
        }
        $params = array();
        $params["cusid"] = self::Config()['cusid'];
        $params["appid"] = self::Config()['appid'];
        $params["version"] = self::Config()['apiversion'];
        $params["trxamt"] = $actualMoney * 100;
        $params["reqsn"] = $ordernumber;//订单号,自行生成
        $params["paytype"] = "W02";
        $params["randomstr"] = rand(100000000000000,999999999999999);//
        $params["body"] = '翻贝网-'.$ordernumber;
        $params["remark"] = $userid;
        $params["acct"] = $openid;
//        $params["limit_pay"] = "no_credit";
        $params["notify_url"] = env('WEB_URL')."fbwnotify/allinpaynotify";
        $params["sign"] = self::SignArray($params);//签名
        $paramsStr = self::ToUrlParams($params);
        $url = self::Config()['apiurl'] . "/pay";
        $rsp = self::request($url, $paramsStr);
        $rspArray = json_decode($rsp, true);
        $data['jsApiParameters'] = $rspArray['payinfo'];
        $data['ordernumber'] = $ordernumber;
        if(self::validSign1($rspArray)){
            return ['status'=>'success','data'=>$data];
        }
        return false;;
    }
    public static function validSign1($array){
        if("SUCCESS"==$array["retcode"]){
            $signRsp = strtolower($array["sign"]);
            $array["sign"] = "";
            $sign =  strtolower(self::SignArray($array));
            if($sign==$signRsp){
                return TRUE;
            }
            else {
                echo "验签失败:".$signRsp."--".$sign;
            }
        }
        else{
            echo $array["retmsg"];
        }

        return FALSE;
    }

    public static function request($url,$params){
        $ch = curl_init();
        $this_header = array("content-type: application/x-www-form-urlencoded;charset=UTF-8");
        curl_setopt($ch,CURLOPT_HTTPHEADER,$this_header);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//如果不加验证,就设false,商户自行处理
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        $output = curl_exec($ch);
        curl_close($ch);
        return  $output;
    }

    public static function SignArray(array $array){
        $array['key'] = self::Config()['appkey'];// 将key放到数组中一起进行排序和组装
        ksort($array);
        $blankStr = self::ToUrlParams($array);
        $sign = md5($blankStr);
        return $sign;
    }

    public static function ToUrlParams(array $array)
    {
        $buff = "";
        foreach ($array as $k => $v)
        {
            if($v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    /**
     * 校验签名
     * @param array 参数
     * @param unknown_type appkey
     */
    public static function ValidSign(array $array){
        $sign = $array['sign'];
        unset($array['sign']);
        $array['key'] = self::Config()['appkey'];
        $mySign = self::SignArray($array);
        return strtolower($sign) == strtolower($mySign);
    }
}